package es.udc.emarketapp.emarket.model.purchase.purchaseFacade.actions;


import es.udc.emarketapp.emarket.model.orderLine.dao.SQLOrderLineDAO;
import es.udc.emarketapp.emarket.model.orderLine.dao.SQLOrderLineDAOFactory;
import es.udc.emarketapp.emarket.model.orderLine.vo.OrderLineVO;
import es.udc.emarketapp.emarket.model.purchase.purchaseFacade.vo.OrderLineChunkVO;


import java.sql.Connection;
import java.util.List;

import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.sql.NonTransactionalPlainAction;

public class FindOrderLinesByOrderAction implements NonTransactionalPlainAction {

	private Long idOrder;
	private Long idPurchase;
	private int startIndex;
	private int count;

	public FindOrderLinesByOrderAction(Long idOrder, Long idPurchase, 
			int startIndex, int count) {

		this.idOrder = idOrder;
		this.idPurchase = idPurchase;
		this.startIndex = startIndex;
		this.count = count;
	}

	/**
	 * 
	 * @return An instance of <code>PurchaseChunkVO</code> objects.
	 */
	public Object execute(Connection connection) throws InternalErrorException {

		/*
		 * Find count+1 purchases to determine if there exist more products
		 * above the specified range.
		 */
		SQLOrderLineDAO orderLineDAO = SQLOrderLineDAOFactory.getDAO();
		List<OrderLineVO> orderLineVOs = orderLineDAO.findByOrder(connection,
				idOrder, idPurchase, startIndex, count + 1);
		boolean existMoreOrderLines = orderLineVOs.size() == (count + 1);

		/*
		 * Remove the last account from the returned list if there exist more
		 * accounts above the specified range.
		 */
		if (existMoreOrderLines) {
			orderLineVOs.remove(orderLineVOs.size() - 1);
		}

		return new OrderLineChunkVO(orderLineVOs, existMoreOrderLines);

	}

}